package web.PetStore.web.servlet;

import web.PetStore.domain.Order;
import web.PetStore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ConfirmOrderServlet",urlPatterns = {"/ConfirmOrder"})
public class ConfirmOrderServlet extends HttpServlet {
    private OrderService orderService = new OrderService();
    private String phone, address;
    private boolean flag = true;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        List<Order> orderList = (List<Order>) session.getAttribute("confirmOrderList");
        this.phone = req.getParameter("phone");
        this.address = req.getParameter("address");

        for(Order order : orderList){
            order.setPhone(phone);
            order.setAddress(address);
            flag &= orderService.addOrder(order);
        }

        if(flag){
            if(orderList.size() == 1){
                session.setAttribute("showingOrder", orderList.get(0));
                req.getRequestDispatcher("/OrderForm").forward(req,resp);
            }else {
                req.getRequestDispatcher("/AccountOrderForm").forward(req,resp);
            }
        }else {
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
